#!/bin/sh
# STDIO mode startup script for Structural Text Analyzer MCP Server
set -e

# Change to project root directory
cd "$(dirname "$0")/.."

# Debug mode - uncomment to enable debugging
# echo "=== DEBUG: Starting MCP Server ===" >&2
# echo "Working directory: $(pwd)" >&2
# echo "Contents: $(ls -la)" >&2

# Load environment variables from .env file if it exists
if [ -f ".env" ]; then
    echo "Loading environment variables from .env file..." >&2
    # Export variables from .env file  
    export $(grep -v '^#' .env | grep -v '^$' | xargs)
fi

# Function to install dependencies
install_dependencies() {
    echo "Installing core dependencies..." >&2
    if command -v uv >/dev/null 2>&1; then
        echo "Using uv package manager..." >&2
        uv add numpy pandas scipy fastmcp python-dotenv
    elif [ -f ".venv/bin/pip" ]; then
        echo "Using venv pip..." >&2
        ./.venv/bin/pip install numpy pandas scipy fastmcp python-dotenv
    else
        echo "Using system pip..." >&2
        pip3 install numpy pandas scipy fastmcp python-dotenv
    fi
}

# Function to run server
run_server() {
    local server_file="$1"
    echo "Starting Structural Text Analyzer MCP Server..." >&2
    
    # Set PYTHONPATH to include src directory
    export PYTHONPATH="$(pwd)/src:$PYTHONPATH"
    
    if command -v uv >/dev/null 2>&1; then
        uv run python "$server_file" --transport stdio
    elif [ -f ".venv/bin/python" ]; then
        ./.venv/bin/python "$server_file" --transport stdio
    else
        python3 "$server_file" --transport stdio
    fi
}

# Create virtual environment if using uv and it doesn't exist
if command -v uv >/dev/null 2>&1; then
    if [ ! -f "pyproject.toml" ] && [ ! -d ".venv" ]; then
        echo "Creating virtual environment..." >&2
        uv venv
    fi
    
    # Check and install dependencies
    if ! uv run python -c "import fastmcp, numpy, pandas, scipy" 2>/dev/null; then
        install_dependencies
    fi
elif [ ! -d ".venv" ]; then
    echo "Creating virtual environment..." >&2
    python3 -m venv .venv
    install_dependencies
fi

# Try to start the main server first, fallback to standalone if it fails
if [ -f "src/structural_analyzer/server.py" ]; then
    echo "Attempting to start main server..." >&2
    if ! run_server "src/structural_analyzer/server.py" 2>/dev/null; then
        echo "Main server failed, trying standalone version..." >&2
        if [ -f "src/structural_analyzer/standalone_server.py" ]; then
            run_server "src/structural_analyzer/standalone_server.py"
        else
            echo "Error: No working server found!" >&2
            exit 1
        fi
    fi
elif [ -f "src/structural_analyzer/standalone_server.py" ]; then
    echo "Using standalone server..." >&2
    run_server "src/structural_analyzer/standalone_server.py"
else
    echo "Error: No server files found!" >&2
    exit 1
fi
